package com.wangp.mywrite.s_netty.netty.ch3;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import java.nio.charset.StandardCharsets;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;

/**
 * @author tooStronger
 * @date 2023/3/19
 */
public class TestByteBuf {

    public static void main(String[] args) {
        // byteBuf 读写
//        writeAndRead();
    }

    private static void writeAndRead() {
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        // class io.netty.buffer.PooledUnsafeDirectByteBuf  -> Pooled 池化   DirectByteBuf 直接内存
        System.out.println(buf.getClass());
        log(buf);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            sb.append("a");
        }
        buf.writeBytes(sb.toString().getBytes(StandardCharsets.UTF_8));
        log(buf);

        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(10);
        buffer.writeBytes(new byte[]{1,2,3,4,5,6,7,8});
        System.out.println(buffer.readByte());
        System.out.println(buffer.readByte());
        System.out.println(buffer.readByte());
        System.out.println(buffer.readByte());
        log(buffer);
        buffer.markReaderIndex();
        System.out.println(buffer.readByte());
        System.out.println(buffer.readByte());
        log(buffer);
        buffer.resetReaderIndex();
        log(buffer);
    }

    public static void log(ByteBuf buffer) {
        int length = buffer.readableBytes();
        int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4;
        StringBuilder buf = new StringBuilder(rows * 80 * 2)
                .append("read index:").append(buffer.readerIndex())
                .append(" write index:").append(buffer.writerIndex())
                .append(" capacity:").append(buffer.capacity())
                .append(NEWLINE);
        appendPrettyHexDump(buf, buffer);
        System.out.println(buf);
    }
}
